package com.iplatform.auth.service.impl;

import com.iplatform.auth.feign.UserCenterClient;
import com.iplatform.module.auth.AuthUserDetailsFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.iplatform.auth.feign.PrivilegeClient;
import com.iplatform.module.privilege.PriManagerBean;
import org.springframework.web.client.RestTemplate;

/**
 * 根据用户名获取用户<br>
 * <p>
 * 密码校验请看下面两个类
 *
 * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
 */
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

	private static final Logger LOG = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private PrivilegeClient privilegeClient;

    @Autowired
    private UserCenterClient userCenterClient;

	@Value("${spring.security.login.enabled-user-center}")
	private boolean enabledUserCenter;

	@Value("${user.center.address:privilege}")
	private String userCenterAddress;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	// 为了支持多用户中心登录，这里username后面拼装上登录类型,如username|userCenter
    	String[] params = username.split("\\|");
		// 真正的用户名
        username = params[0];
    	LOG.info("尝试获取当前用户信息:{}", username);

    	String serviceId=null;
    	if(params.length>=2){
			//用户中心服务id
			serviceId=params[1];
			LOG.info("当前用户中心:{}", serviceId);
		}

    	PriManagerBean loginAppUser = null;
    	//是否启用用户中心
		LOG.info("enabledUserCenter:{}", enabledUserCenter);

    	if(enabledUserCenter) {
    		//若用户中心服务id不为空，则动态调用获取用户方法，否则调用默认用户中心
    		if(StringUtils.isNotBlank(serviceId)){
				AuthUserDetailsFacade facade = userCenterClient.getManager(serviceId,username).getBody();
				facade.setUserServiceId(serviceId);
				return facade;
			}else {
				loginAppUser = privilegeClient.getManager(username).getBody();
			}
			LOG.info("loginAppUser:{}", loginAppUser);
    	}else {
	    	//当没用户中心时启用测试账号
	    	loginAppUser = new PriManagerBean();
	    	loginAppUser.setUserCode("admin");
	    	loginAppUser.setUserName("超级管理员");
	    	loginAppUser.setPassword("96E79218965EB72C92A549DD5A330112");
	    	loginAppUser.setIsEnable(true);
    	}

		LOG.info("已从权限中心获取当前用户信息:{}", loginAppUser);
        if (loginAppUser == null) {
        	LOG.info("用户不存在:{}", username);
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        }
//        else if (!loginAppUser.getIsEnable()) {
//        	LOG.info("用户已作废:{}", username);
//            throw new DisabledException("用户已作废");
//        }
        return loginAppUser;
    }


}
